package com.studyroom.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studyroom.common.Result;
import com.studyroom.entity.SnackOrder;
import com.studyroom.service.SnackOrderService;
import com.studyroom.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/snack-orders")
public class SnackOrderController {

    @Autowired
    private SnackOrderService snackOrderService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping
    public Result<?> create(@RequestBody SnackOrder order, 
                          @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            snackOrderService.createOrder(username, order);
            return Result.success("下单成功");
        }
        return Result.error("下单失败");
    }

    @GetMapping("/my")
    public Result<Page<SnackOrder>> getMyOrders(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            return Result.success(snackOrderService.getMyOrders(username, status, new Page<>(page, size)));
        }
        return Result.error("获取订单列表失败");
    }

    @PutMapping("/{id}/cancel")
    public Result<?> cancel(@PathVariable Long id,
                          @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            snackOrderService.cancelOrder(username, id);
            return Result.success("取消成功");
        }
        return Result.error("取消失败");
    }
} 